<?php

namespace control;
//管理员后台-库存分布

class inventoryDistributionClass extends adIndexClass
{
    private const title                  = '库存分布';
    private const page                   = 'inventoryDistribution';
    private const table                  = 'inventory_record';
    private const tableWarehouse         = 'warehouse';
    private const tableWarehousePosition = 'warehouse_position';
    private const tableMaterial          = 'material';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'warehouse'  => [
                        'name'  => '{l.inventoryDistribution.homeSearch.warehouse}',
                        'width' => 150,
                    ],
                    'position'   => [
                        'name'  => '{l.inventoryDistribution.homeSearch.position}',
                        'width' => 150,
                    ],
                    'code'       => [
                        'name'  => '{l.inventoryDistribution.homeSearch.code}',
                        'width' => 150,
                    ],
                    'name'       => [
                        'name'  => '{l.inventoryDistribution.homeSearch.name}',
                        'width' => 150,
                    ],
                    'typeName'   => [
                        'name'  => '{l.inventoryDistribution.homeSearch.type}',
                        'width' => 100,
                    ],
                    'model'      => [
                        'name'  => '{l.inventoryDistribution.homeSearch.model}',
                        'width' => 150,
                    ],
                    'batch'      => [
                        'name'  => '{l.inventoryDistribution.homeSearch.batch}',
                        'width' => 200,
                        'sort'  => 1,
                    ],
                    'unit'       => [
                        'name'  => '{l.inventoryDistribution.homeSearch.unit}',
                        'width' => 80,
                    ],
                    'total'      => [
                        'name'  => '{l.inventoryDistribution.homeSearch.num}',
                        'width' => 100,
                        'sort'  => 1,
                    ],
                    'unit_one'   => [
                        'name'  => '{l.inventoryDistribution.homeSearch.unit_one}',
                        'width' => 80,
                    ],
                    'unitOneNum' => [
                        'name'  => '{l.inventoryDistribution.homeSearch.unit_one_num}',
                        'width' => 100,
                    ],
                    'unit_two'   => [
                        'name'  => '{l.inventoryDistribution.homeSearch.unit_two}',
                        'width' => 80,
                    ],
                    'unitTwoNum' => [
                        'name'  => '{l.inventoryDistribution.homeSearch.unit_two_num}',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $id = suiji();
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('inventoryDistribution.home.warehouse') => idSelect([
                        'name'     => 'warehouseId',
                        'sqlForm'  => self::tableWarehouse . " WHERE coid = '" . self::$coid . "' AND state = '启用' " . self::getWarehouseSql(),
                        'sqlId'    => 'id',
                        'sqlField' => "name",
                        'change'   => "getPosition, $id"
                    ]),
                    L('inventoryDistribution.home.position')  => select(["name" => "positionId", 'id' => $id]),
                    L('inventoryDistribution.home.name')      => text(["name" => "mName"]),
                ],
                [
                    L('inventoryDistribution.home.code')  => text(array("name" => "mCode")),
                    L('inventoryDistribution.home.type')  => materialClass::typeSelect(name: 'mTypeId', title: '请选择'),
                    L('inventoryDistribution.home.batch') => text(["name" => "batch"]),
                ]
            ]
        ], 1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 查询表单
     *
     * @return string
     */
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url    = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "export")) {
            $button .= "<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'" . self::page . "'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*列表页-查询结果*/
    public function homeSearch(): bool|string
    {
        //查询结果
        $where = ' 1=1 ';
        $equal = [
            'a.coid'        => self::$coid,
            'a.warehouseId' => $this->post('warehouseId'),
            'a.positionId'  => $this->post('positionId'),
        ];
        $like  = [
            'a.batch' => $this->post('batch'),
            'b.typePath' => $this->post('mTypeId'),
            'b.code' => $this->post('mCode'),
            'b.name' => $this->post('mName'),
        ];
        //生成查询语句
        $where       .= search([
            "="    => $equal,
            "like" => $like,
        ]);
        $where        .= self::getWarehouseSql('warehouseId');
        $fieldArr     = self::resolveField([
            'field' => 'a.`id`, a.`coid`, a.`warehouseId`, a.`positionId`, a.`materialId`, a.`batch`, a.`num`, a.`inventoryId`, a.`inventoryMxId`, a.`moveId`, a.`isDefault`, a.`defaultPrice`, a.`time`, SUM(a.num) as total, b.`downStock`, b.`upStock`, b.`unit_one`, b.`unit_two`, b.`unit_one_num`, b.`unit_two_num`, b.`code`, b.`name`, b.`typeName`, b.`model`, b.`unit`',
            'group' => 'a.materialId, a.batch, a.positionId',
        ]);
        $outAllowZero = optionSettingClass::getSettingItem('库存', 'outAllowZero');//允许零库存出库
        $having       = "";
        if (!$outAllowZero) {
            $having = " HAVING `total` > 0 ";
        }
        //排序
        $orderBy                     = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        $page                        = $this->page([
            'field' => $fieldArr['field'],
            "table" => self::table . " as a join material as b on a.materialId = b.id",
            "where" => $where . $fieldArr['group'] . $having,
            "order" => $orderBy['orderBy']
        ]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'total':
                        $row[] = self::lostZero($array['total'], 'numPrecision');
                        break;
                    case 'warehouse':
                        $row[] = warehouseClass::getName($array['warehouseId']);
                        break;
                    case 'position':
                        $row[] = warehousePositionClass::getName($array['positionId']);
                        break;
                    case 'unitOneNum':
                        $unitOneNum = (!$array['unit_one'] || empty((float)$array['unit_one_num'])) ? '' : self::formattingFigure($array['total'] / $array['unit_one_num'], 'numPrecision');
                        $row[]      = self::lostZero($unitOneNum, 'numPrecision');
                        break;
                    case 'unitTwoNum':
                        $unitTwoNum = (!$array['unit_two'] || empty((float)$array['unit_two_num'])) ? '' : self::formattingFigure($array['total'] / $array['unit_two_num'], 'numPrecision');
                        $row[]      = self::lostZero($unitTwoNum, 'numPrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $html = <<<EOT
<script>
function getPosition(that, id) {
  const waid = $(that).val()
  $.post(root+'control/adIndex.html?cla=inventoryDistribution&fun=getPosition', {waid: waid}, function(res) {
  	$('#'+id).html(res.html)
  }, 'json')
}
</script>
EOT;
        $totalQuery = find([
            'table'  => self::table . " as a join material as b on a.materialId = b.id",
            'single' => $where,
            'field'  => "ifnull(sum(a.num),0) as num,ifnull(sum(a.num/b.unit_one_num),0) as unitOneNum,ifnull(sum(a.num/b.unit_two_num),0) as unitTwoNum",
        ]);
        $total    = [
            'total'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'unitOneNum'   => self::lostZero($totalQuery['unitOneNum'], 'numPrecision'),
            'unitTwoNum' => self::lostZero($totalQuery['unitTwoNum'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . $html;
        return json_encode($json, 320);
    }

    /**
     * 获取仓位
     *
     * @return string
     */
    public function getPosition(): string
    {
        $id   = $this->post('waid');
        $html = idSelect([
            'name'     => 'positionId',
            'sqlForm'  => self::tableWarehousePosition . " WHERE coid = '" . self::$coid . "' AND orderId = '$id' AND state = '启用' ORDER BY name ",
            'sqlId'    => 'id',
            'sqlField' => "name",
            'title'    => L('inventoryDistribution.homeSearch.position'),
        ]);
        return json_encode(['html' => $html], 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId     = $this->get('templateId');
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            /***********标题**********/
            $title        = [];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']) {
                    $title[] = $array['aliasName'];
                }
            }
            $sql    = $_SESSION[self::page]['sql'];
            $result = sqlFind($sql);
            //导出数据生成
            foreach ($result as $array) {
                $column     = [];
                $material   = query(
                    self::tableMaterial,
                    " id = '$array[materialId]' ",
                    'code, name, model, unit, unit_one, unit_one_num, unit_two, unit_two_num, typeId, typeName'
                );
                $total      = $array['total'];
                $unitOneNum = (!$material['unit_one'] || empty((float)$material['unit_one_num'])) ? '' : self::formattingFigure($total / $material['unit_one_num'], 'numPrecision');
                $unitTwoNum = (!$material['unit_two'] || empty((float)$material['unit_two_num'])) ? '' : self::formattingFigure($total / $material['unit_two_num'], 'numPrecision');
                foreach ($tempFieldAll as $templateField) {
                    if ($templateField['display']) {
                        $column[] = match ($templateField['columnName']) {
                            '仓库' => warehouseClass::getName($array['warehouseId']),
                            '仓位' => warehousePositionClass::getName($array['positionId']),
                            '物料编码' => $material['code'],
                            '物料名称' => $material['name'],
                            '物料分类' => $material['typeName'],
                            '规格型号' => $material['model'],
                            '批次' => $array['batch'],
                            '主单位' => $material['unit'],
                            '主单位数量' => self::lostZero($total, 'numPrecision'),
                            '辅单位1' => $material['unit_one'],
                            '辅单位1数量' => self::lostZero($unitOneNum, 'numPrecision'),
                            '辅单位2' => $material['unit_two'],
                            '辅单位2数量' => self::lostZero($unitTwoNum, 'numPrecision'),
                            default => '',
                        };
                    }
                }
                $data[] = $column;
            }

            $text = str_replace(['{{staffName}}'], [$this->control['name']], lang('inventoryDistribution.exportData.log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title . ".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify = ''): array
    {
        return match ($classify) {
            default => [
                [
                    'columnName' => '仓库',
                    'aliasName'  => '仓库',
                ],
                [
                    'columnName' => '仓位',
                    'aliasName'  => '仓位',
                ],
                [
                    'columnName' => '物料编码',
                    'aliasName'  => '物料编码',
                ],
                [
                    'columnName' => '物料名称',
                    'aliasName'  => '物料名称',
                ],
                [
                    'columnName' => '物料分类',
                    'aliasName'  => '物料分类',
                ],
                [
                    'columnName' => '规格型号',
                    'aliasName'  => '规格型号',
                ],
                [
                    'columnName' => '批次',
                    'aliasName'  => '批次',
                ],
                [
                    'columnName' => '主单位',
                    'aliasName'  => '主单位',
                ],
                [
                    'columnName' => '主单位数量',
                    'aliasName'  => '主单位数量',
                ],
                [
                    'columnName' => '辅单位1',
                    'aliasName'  => '辅单位1',
                ],
                [
                    'columnName' => '辅单位1数量',
                    'aliasName'  => '辅单位1数量',
                ],
                [
                    'columnName' => '辅单位2',
                    'aliasName'  => '辅单位2',
                ],
                [
                    'columnName' => '辅单位2数量',
                    'aliasName'  => '辅单位2数量',
                ],
            ]
        };
    }
}
